package com.cloudxingkong.dianyinke.NewTeacher.Fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Adapter.DTLVAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Ui.DontaiDetailActivity;
import com.cloudxingkong.dianyinke.NewTeacher.Ui.PostDongTai;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.bean.TeacherDT;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 云星空科技 on 2016/3/18.
 */
public class DongTaiFragment extends BaseFragment implements View.OnClickListener, DTLVAdapter.getOnTouchDTPosition {

    private ListView listView;
    private List<TeacherDT.ListBean> list;
    private LinearLayout postDTLayout;
    private SharedPreferences sharedPreferences;
    private String sessionID;
    private ProgressBar progressBar;
    private DTLVAdapter dtlvAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dongtai, null);
        View headView = View.inflate(getActivity(), R.layout.layout_dongtai, null);
        progressBar = (ProgressBar) view.findViewById(R.id.pb_dongtai);
        listView = (ListView) view.findViewById(R.id.cl_dongtai_listview);
        postDTLayout = (LinearLayout) view.findViewById(R.id.post_dongtai_layout);
        postDTLayout.addView(headView);
        list = new ArrayList<>();

        dtlvAdapter = new DTLVAdapter(list, getActivity(), this);
        listView.setAdapter(dtlvAdapter);

        sharedPreferences = getActivity().getSharedPreferences("data_dyk", 0);
        sessionID = CookieHelper.getSessionID(sharedPreferences);

        loadDongTaiList();

        //发布动态
        postDTLayout.setOnClickListener(this);

        return view;
    }

    private void loadDongTaiList() {
        progressBar.setVisibility(View.VISIBLE);
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.NAMICS_QRYDY);
        params.addHeader("cookie", sessionID);

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "老师获取动态列表 " + result);
                if (result != null && !result.equals("")) {
                    Message msg = handler.obtainMessage();
                    msg.what = 1;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } else {
                    handler.sendEmptyMessage(2);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressBar.setVisibility(View.GONE);
                handler.sendEmptyMessage(3);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String result = (String) msg.obj;
                    progressBar.setVisibility(View.GONE);
                    try {
                        Gson gson = new Gson();
                        TeacherDT dt = gson.fromJson(result, TeacherDT.class);
                        if (dt.getList() != null && dt.getList().size() > 0) {
                            list.clear();
                            list.addAll(dt.getList());
                            dtlvAdapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(getActivity(), "获取动态失败", Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        Log.e("test", "老师动态截取异常 " + e.getMessage());
                        Toast.makeText(getActivity(), "还没有动态哦~快去发布一条吧！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                case 3:
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), "获取动态失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), PostDongTai.class);
        startActivityForResult(intent, 315);
    }

    /**
     * 发布动态成功or删除动态成功后的操作
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 315) {
            if (resultCode == 316 || resultCode == 318) {
                loadDongTaiList();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 适配器回调
     *
     * @param position
     */
    @Override
    public void getPosition(int position) {
        //点击动态列表条目
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {

                    String dtID = list.get(position).getId() + "";
                    String text = list.get(position).getText() + "";

                    Object memname = list.get(position).getMemname();

                    Intent intent = new Intent(getActivity(), DontaiDetailActivity.class);
                    Log.e("test", "点击动态条目中的动态ID " + dtID);
                    intent.putExtra("dtID", dtID);
                    intent.putExtra("text", text);
                    intent.putExtra("tMemname", memname == null ? "" : memname.toString());
                    startActivityForResult(intent, 315);
                } catch (Exception e) {
                    Log.e("test", "截取动态条目异常 " + e.getMessage());
                }
            }
        });
    }

}
